package com.freight.auth.controller;

import com.freight.auth.form.AppLoginBody;
import com.freight.auth.form.AppRegisterBody;
import com.freight.auth.service.AppLoginService;
import com.freight.common.core.constant.*;
import com.freight.common.core.domain.R;
import com.freight.common.core.utils.StringUtils;
import com.freight.common.security.service.AppTokenService;
import com.freight.common.security.utils.SecurityUtils;
import com.freight.tws.api.model.LoginDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

/**
 * 手机APP端
 */
@RestController
@RequestMapping(Constants.APP_URL + "/")
@Validated
public class AuthController {

    @Autowired
    private AppLoginService loginService;

    @Autowired
    private AppTokenService appTokenService;

    /**
     * 登陆
     * @param form
     * @return
     */
    @PostMapping("loginByPhone")
    public R<?> loginByPhone(@RequestBody @Valid AppLoginBody form) {
        LoginDriver loginDriver = loginService.login(form.getPhone(), form.getPassword());
        // 获取登录token
        Map<String, Object> token = appTokenService.createToken(loginDriver);
        token.put("driver", loginDriver);
        return R.ok(token);
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request) {
        LoginDriver loginDriver = appTokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginDriver)) {
            return R.ok(appTokenService.refreshToken(loginDriver));
        }
        return R.fail();
    }

    /** 从缓存获取最新的司机信息 */
    @PostMapping("getNewUserInfoByCache")
    public R<?> getNewUserInfoByCache(HttpServletRequest request) {
        LoginDriver loginDriver = appTokenService.getLoginUser(request);
        return R.ok(loginDriver);

    }

    /**
     * 退出
     */
    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            appTokenService.delLoginUser(token);
        }
        return R.ok();
    }

    /**
     * 注册
     * @return
     */
    @PostMapping("regist")
    public R<?> regist(@RequestBody AppRegisterBody registerBody) {
        loginService.register(registerBody);
        return R.ok();
    }

}
